package com.gtw.modules.api.controller;

import com.gtw.common.annotation.AuthIgnoreApi;
import com.gtw.common.utils.R;
import com.gtw.utils.FastDFSClientWrapper;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Map;

/**
 * Created by wuye on 2018/3/26.
 */
@RestController
@RequestMapping("/api")
public class ApiFileUploadController {

    @Autowired
    private FastDFSClientWrapper fastDFSClientWrapper;


    @AuthIgnoreApi
    @PostMapping(value = "/uploadimage")
    public Map fileUpload(MultipartFile upfile) throws IOException {
        try {
            String fileName = upfile.getOriginalFilename();
            String address = fastDFSClientWrapper.uploadFile(upfile);
            Map<String,Object> result = new HashedMap();
            result.put("state","SUCCESS");
            result.put("url",address);
            result.put("title",fileName);
            return result;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

    @AuthIgnoreApi
    @PostMapping(value = "/uploadimage3")
    public R fileUpload3(MultipartFile upfile) throws IOException {
        String address = fastDFSClientWrapper.uploadFile(upfile);
        return R.ok().put("data",address);
    }

    @AuthIgnoreApi
    @RequestMapping("/uploadimage2")
    public Map fileUpload2(@RequestParam("upImage") File upImage) throws IOException {
        try {
            String fileName = upImage.getName();
            String address = fastDFSClientWrapper.fileUpload2(upImage);
            Map<String,Object> result = new HashedMap();
            result.put("state","SUCCESS");
            result.put("url",address);
            result.put("title",fileName);
            return result;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }

    }

    @AuthIgnoreApi
    @RequestMapping("/delete")
    public R deletFile(String fileAddress){
        fastDFSClientWrapper.deleteFile(fileAddress);
        return R.ok();
    }
}
